<?php
# http://projects:8081/cdapp-2kt-api/api/activity_plan_military_load.php

include_once '_portal.php';
include_once '_envs.php';
include_once 'request_sipds.php';
include_once 'request_sipds_soap_lib.php';

define('PARAM_NAME', 'activityPlanMilitaryLoad');
define('MIN_TTL', 1000 * 60 * 3);
define('MAX_TTL', 1000 * 60 * 6);
define('API_CONTENT', SIPDS_API['空军计划']);
define('TABLE_NAME', '2kt_activity_plan_military');

$start_date = isset($GET['start']) ? $GET['start'] : date('Y-m-d');
$end_date = isset($GET['end']) ? $GET['end'] : date('Y-m-d', strtotime('tomorrow'));

main($start_date, $end_date);
function main($start_date, $end_date) {
  $start_date_timestamp = strtotime($start_date);
  $end_date_timestamp = strtotime($end_date);
  if ($start_date_timestamp >= $end_date_timestamp) {
    output([
      'status' => -1,
      'result' => 'error',
      'msg' => 'Start date should be before end date!',
      'content' => [],
    ]);
    die();
  } else {
    $refresh_info = get_param(PARAM_NAME);
    if (!$refresh_info) {
      $refresh_info = ['tx' => 0, 'rx' => 1];
    }
    $ttl_verify = verify_ttl($refresh_info['tx'], $refresh_info['rx'], MIN_TTL, MAX_TTL);
    $info = 'activity_oma_load: ' . $ttl_verify['info'];
    $status = $ttl_verify['status'];
    $time = $ttl_verify['time'];

    if ($status > 0) {
      save_param(PARAM_NAME, ['tx' => $time, 'rx' => $refresh_info['rx']]);
      $loading_res = load_data($start_date, $end_date);
      $info .= ' ' . $loading_res['info'];
      $status = $status * $loading_res['status'];
      $time_rx = timestamp();
      save_param(PARAM_NAME, ['tx' => $time, 'rx' => $time_rx]);
    }

    output([
      'status' => $status,
      'result' => 'success',
      'msg' => $info,
      'content' => [],
    ]);

    die();
  }
}

function load_data($start_date, $end_date) {
  $api_xml = str_replace(API_CONTENT['end'], $end_date, str_replace(API_CONTENT['start'], $start_date, API_CONTENT['xml']));
  $api_url = API_CONTENT['url'];
  $api_content = [
    'url' => $api_url,
    'xml' => $api_xml,
  ];
  $response = request_sipds($api_content, false);

  if ($response['status'] == 0) {
    return [
      'status' => -2,
      'info' => 'Failed to refresh data, sending request failed.',
    ];
  }
  if (!isset($response['data']['CONTENTS']) || $response['data']['CONTENTS'] == null) {
    return [
      'status' => -3,
      'info' => 'Failed to refresh data, recived null response.',
    ];
  } else {
    $table_name = TABLE_NAME;
    $sql = "DELETE FROM `{$table_name}` WHERE `date` >= '{$start_date}' AND `date` <= '{$end_date}';";
    $sql .= "INSERT INTO `{$table_name}` (`name`, `unit`, `arrField`, `depField`, `date`, `fullATD`, `ATD`, `ETA`, `ETD`, `route`, `remark`) VALUES ";
    foreach ($response['data']['CONTENTS'] as $res) {
      $element = [
        'name' => $res['FLTID'],
        'unit' => $res['UNIT'],
        'arrField' => $res['ARRAP'],
        'depField' => $res['DEPAP'],
        'date' => substr($res['WHICHDAY'], 0, 10) . ' ' . substr($res['WHICHDAY'], 11, 8),
        'fullATD' => substr($res['ATD'], 0, 10) . ' ' . substr($res['ATD'], 11, 8),
        'ATD' => $res['ATTRI2'],
        'ETA' => $res['ETA'],
        'ETD' => $res['ETD'],
        'route' => $res['ROUTE'],
        'remark' => (isset($res['USERMEMO']) ? $res['USERMEMO'] : '') . (isset($res['HEIGHT']) ? $res['HEIGHT'] : ''),
      ];
      $sql .= "('{$element['name']}', '{$element['unit']}', '{$element['arrField']}', '{$element['depField']}', '{$element['date']}', '{$element['fullATD']}', '{$element['ATD']}', '{$element['ETA']}', '{$element['ETD']}', '{$element['route']}', '{$element['remark']}'),";
    }
    $sql = rtrim($sql, ',');
    $sql .= ';';
    $status = exec_sql($sql);
    return [
      'status' => $status,
      'info' => $status ? 'loaded' : 'update failed',
    ];
  }
}